import com.itbaizhan.mapper.UserMapper;
import com.itbaizhan.pojo.User;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
/*注解式开发二级缓存
* 运行第二次时，没有执行sql语句，直接从二级缓存中取到对象*/
public class UserMapper2 {
    @Test
    public void testCache() throws IOException {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(is);

        SqlSession session1 = factory.openSession();
        SqlSession session2 = factory.openSession();
         UserMapper userMapper1 = session1.getMapper(UserMapper.class);
        UserMapper userMapper2 = session2.getMapper(UserMapper.class);

        User user = userMapper1.findById(1);
        System.out.println(user);
        System.out.println(user.hashCode());
        session1.commit();//清空一级缓存，将数据存放在二级缓存
        System.out.println("--------------");
        User user1 = userMapper2.findById(1);
        System.out.println(user1);
        System.out.println(user1.hashCode());


        session1.close();
        session2.close();
        is.close();
    }
}
/*MyBatis默认开启一级缓存，接下来我们学习如何在注解开发时使用二级缓存：

POJO类实现Serializable接口。

在MyBatis配置文件添加如下设置：
默认是true,可以不写
<settings>
  <setting name="cacheEnabled" value="true"/>
</settings>
在 持久层接口上方 加注解@CacheNamespace(blocking=true)，该接口的所有方法都支持二级缓存。*/